/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.adapter.driving.persistence.dict.repository;

import com.lap.auth.adapter.driving.persistence.dict.DictCache;
import com.lap.auth.adapter.driving.persistence.dict.DictConverter;
import com.lap.auth.adapter.driving.persistence.dict.mapper.DictMapper;
import com.lap.auth.adapter.driving.persistence.dict.po.DictPo;
import com.lap.auth.domain.dict.Dict;
import com.lap.auth.domain.dict.repository.DictRepository;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class DictRepositoryImpl implements DictRepository {

  private final DictConverter dictConverter;
  private final DictMapper dictMapper;

  @CacheEvict(
      value = {DictCache.DICT},
      allEntries = true)
  @Override
  public void saveAll(List<Dict> sources) {
    dictMapper.insertBatch(dictConverter.toPoList(sources));
  }

  @CacheEvict(
      value = {DictCache.DICT},
      allEntries = true)
  @Override
  public void deleteByDictTypeCode(String dictTypeCode) {
    dictMapper.deleteByDictTypeCode(dictTypeCode);
  }

  @Override
  public List<Dict> findByDictTypeCode(String dictTypeCode) {
    List<DictPo> sources = dictMapper.selectByDictTypeCode(dictTypeCode);
    return dictConverter.toDomains(sources);
  }

  @Cacheable(
      value = {DictCache.DICT},
      key = "T(com.lap.auth.shared.tools.CacheKeyUtil).generateKey(#dictTypeCodes,#lang)",
      unless = "#result == null")
  @Override
  public List<Dict> findByDictTypeCode(List<String> dictTypeCodes, String lang) {
    List<DictPo> sources = dictMapper.selectByDictCode(dictTypeCodes, lang);
    return dictConverter.toDomains(sources);
  }
}
